//播放器组件
import 'package:chewie/chewie.dart' hide MaterialControls;
import 'package:flutter/material.dart';
import 'package:hi_base/color.dart';
import 'package:hi_base/view_util.dart';
import 'package:video_player/video_player.dart';

import 'hi_video_controls.dart';

class VideoView extends StatefulWidget {
  final String url;
  final String? cover;
  final bool autoPlay;
  final bool looping;
  final double aspectRatio;
  final Widget overlayUI;

  const VideoView(
    this.url, {
    super.key,
    this.cover,
    this.autoPlay = true,
    this.looping = true,
    this.aspectRatio = 16 / 9,
    required this.overlayUI,
  });

  @override
  State<VideoView> createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  /*
  final videoPlayerController = VideoPlayerController.network(
    'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');

await videoPlayerController.initialize();

final chewieController = ChewieController(
  videoPlayerController: videoPlayerController,
  autoPlay: true,
  looping: true,
);

final playerWidget = Chewie(
  controller: chewieController,
);
   */
  late VideoPlayerController
      _videoPlayerController; //video_player 播放器的controller
  late ChewieController _chewieController;
  //封面
  get _placeholder => FractionallySizedBox(
        widthFactor: 1, //充满整个屏幕
        child: cachedImage(widget.cover!!),
      );

  //进度条颜色设置
  get _progressColors => ChewieProgressColors(
      playedColor: primary,
      handleColor: primary,
      backgroundColor: Colors.grey,
      bufferedColor: Colors.white38);

  @override
  void initState() {
    super.initState();
    //初始化播放器设置
    _videoPlayerController =
        VideoPlayerController.networkUrl(Uri.parse(widget.url));

    _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: widget.autoPlay, //是否自动播放
        looping: widget.looping, //是否寻欢播放
        aspectRatio: widget.aspectRatio, //
        allowMuting: false,
        materialProgressColors: _progressColors,
        placeholder: _placeholder, //设置默认 placeholder
        customControls: MaterialControls(
          showLoadingOnInitialize: false,
          showBigPlayIcon: false,
          bottomGradient: blackLinearGradient(),
          overlayUI: widget.overlayUI,
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double playerHeight = screenWidth / widget.aspectRatio;
    return Container(
      width: screenWidth,
      height: playerHeight,
      color: Colors.grey,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }
}
